package com.zx.sdk

import java.security.MessageDigest
import java.util.TreeMap

class SingUtils {

    fun generatingRandomString(): String {
        var randomCode = ""
        val model = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"
        val m = model.toCharArray()
        for (j in 0..5) {
            val c = m[(Math.random() * 52).toInt()]
            randomCode += c
        }
        return randomCode
    }

    fun sign(
        secret:String,
        paramsMap: TreeMap<String, String>,
        nonceStr: String,
        timestamp: String
    ): String {
        val key  = "ssp"
        val query = paramsMap.map { (k, v) ->
            "$k=$v"
        }.reduce { p1, p2 -> "$p1&$p2" }
        return md5("$query$key$secret$nonceStr$timestamp")
    }

    private fun md5(content: String): String {
        val hash = MessageDigest.getInstance("MD5").digest(content.toByteArray())
        val hex = StringBuilder(hash.size * 2)
        for (b in hash) {
            var str = Integer.toHexString(b.toInt())
            if (b < 0x10) {
                str = "0$str"
            }
            hex.append(str.substring(str.length - 2))
        }
        return hex.toString()
    }
}